from flask import abort
from flask import current_app, jsonify
from flask import g
from flask import render_template
from flask import request


from info import constants
from info.models import News, Category
from info.utils.common import user_login_data
from info.utils.response_code import RET
from . import index_blue


@index_blue.route('/news_list')
def news_list():
    """
    获取首页新闻数据
    :return:
    """

    # 1. 获取参数
    # 新闻的分类id
    cid = request.args.get("cid", "1")
    page = request.args.get("page", "1")
    per_page = request.args.get("per_page", "10")

    # 2. 校验参数
    try:
        page = int(page)
        cid = int(cid)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数")

    filters = [News.status!=1]

    if cid != 1:  # 查询的不是最新的数据
        # 需要添加条件
        filters.append(News.category_id == cid)

    # 3. 查询数据
    try:
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page, per_page, False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")

    # 取到当前页的数据
    news_model_list = paginate.items  # 模型对象列表
    total_page = paginate.pages
    current_page = paginate.page

    # 将模型对象列表转成字典列表
    news_dict_li = []
    for news in news_model_list:
        news_dict_li.append(news.to_basic_dict())

    data = {
        "total_page": total_page,
        "current_page": current_page,
        "news_dict_li": news_dict_li
    }

    return jsonify(errno=RET.OK, errmsg="OK", data=data)

@index_blue.route('/')
@user_login_data
def index():
    # 需要在用户请求首页的时候去数据库查询用户数据
    # 如果查询到用户数据，则传入模板中，进行渲染，再进行返回
    # 如果未查询到，返回用户数据为
    # None，模板代码中自行判断
    # 获取当前用户的id
    # user_id = session.get('user_id')
    # user=None
    # if user_id:
    #     try:
    #         user = User.query.get(user_id)
    #     except Exception as e:
    #         current_app.logger.error(e)
    #         return jsonify(errno=RET.DATAERR, errmsg="数据查询错误")
    user = g.user

    # 获取点击排行
    news_list=None
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg="数据查询错误")

    news_list_li=[]
    for new in news_list:
        # 便利得到的是数据模型的对象，所以需要调用模型的方法，转化为字典形式的数据
        news_list_li.append(new.to_basic_dict())

    # 获取新闻分类列表的数据
    categories=None
    try:
        categories=Category.query.order_by(Category.id).limit(constants.HOME_PAGE_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg="数据查询错误")

    categories_list=[]
    for new in categories:
        categories_list.append(new)

    data = {
        'user': user.to_dict() if user else None,
        'news_dict_li':news_list_li,
        'categories':categories_list
    }
    return render_template('news/index.html', data=data)


@index_blue.route('/favicon.ico')
def favicon():
    return current_app.send_static_file('news/favicon.ico')
